package com.example.administrator.random;

import android.content.Context;
import android.text.TextUtils;
import de.robv.android.xposed.IXposedHookLoadPackage;
import de.robv.android.xposed.XC_MethodHook;
import de.robv.android.xposed.XposedBridge;
import de.robv.android.xposed.XposedHelpers;
import de.robv.android.xposed.callbacks.XC_LoadPackage;

//https://github.com/veryyoung/RandomGame.git
public class RandomHook implements IXposedHookLoadPackage {

	public static final String WECHAT_PACKAGE_NAME = "com.tencent.mm";

	// 微信版本号
	private static String wechatVersion = "";

	@Override
	public void handleLoadPackage(XC_LoadPackage.LoadPackageParam lpp) throws Throwable {

		// filter
		if (!lpp.packageName.equals(WECHAT_PACKAGE_NAME)) {
			return;
		}

		if (TextUtils.isEmpty(wechatVersion)) {
			Context context = (Context) (Context) XposedHelpers.callMethod(
					XposedHelpers.callStaticMethod(XposedHelpers.findClass("android.app.ActivityThread", null),
							"currentActivityThread", new Object[0]), "getSystemContext", new Object[0]);
			String versionName = context.getPackageManager().getPackageInfo(lpp.packageName, 0).versionName;
			XposedBridge.log("Random Hook,Found wechat version:" + versionName);
			this.wechatVersion = versionName;
			VersionParam.init(wechatVersion);
		}

		int paramSize = VersionParam.paramSize;
		if (paramSize == 1) {
			XposedHelpers.findAndHookMethod(VersionParam.randomGameClass, lpp.classLoader, VersionParam.gameType,
					int.class, new XC_MethodHook() {
						@Override
						protected void afterHookedMethod(MethodHookParam param) {
							handleHook(param);
						}
					});
		} else if (paramSize == 2) {
			XposedHelpers.findAndHookMethod(VersionParam.randomGameClass, lpp.classLoader, VersionParam.gameType,
					int.class, int.class, new XC_MethodHook() {
						@Override
						protected void afterHookedMethod(MethodHookParam param) {
							handleHook(param);
						}
					});
		}

	}

	private void handleHook(XC_MethodHook.MethodHookParam param) {
		int gameType = ((Integer) param.args[0]).intValue();
		XposedBridge.log("Random Hook,gameType:" + gameType);
		int num = 0;
		switch (gameType) {
		case 2:// 剪刀石头布
			if (PreferencesUtils.moraCheat()) {
				num = PreferencesUtils.moraNum();
				XposedBridge.log("Random Hook,Number:" + num);
				param.setResult(num);
			}
			break;
		case 5:// 骰子
			if (PreferencesUtils.diceCheat()) {
				num = PreferencesUtils.diceNum();
				XposedBridge.log("Random Hook,Number:" + num);
				param.setResult(num);
			}
		default:
		}
	}
}
